<template>
  <div class="contest-list-container">
    <div class="page-header">
      <h2>竞赛广场</h2>
      <div class="header-actions">
        <el-button 
          v-if="canCreateContest"
          type="primary" 
          :icon="Plus" 
          @click="goToCreateContest" 
          round
        >
          创建竞赛
        </el-button>
        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索竞赛标题"
            class="filter-item"
            prefix-icon="Search"
            @input="handleSearch"
            clearable
          />
          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            class="filter-item"
            @change="handleFilter"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
    </div>

    <el-row :gutter="20" class="contest-list">
      <el-col
        v-for="contest in displayContests"
        :key="contest.id"
        :xs="24"
        :sm="12"
        :md="12"
        :lg="12"
        :xl="8"
        class="contest-item-col"
      >
        <el-card class="contest-card" shadow="hover" :body-style="{ padding: '0px' }">
          <div class="contest-cover">
            <el-image
              :src="contest.coverImage || require('@/assets/images/1.png')"
              fit="cover"
              class="cover-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon size="30"><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="contest-status" :class="getStatusClass(contest.status)">
              {{ getStatusText(contest.status) }}
            </div>
          </div>
          <div class="contest-info">
            <h3 class="contest-title">{{ contest.title }}</h3>
            <p class="contest-description">{{ truncateText(contest.description, 80) }}</p>
            <div class="contest-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(contest.startTime) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ contest.currentParticipants }} 人参与</span>
              </div>
            </div>
            <div class="contest-actions">
              <el-button type="primary" round @click="viewContestDetail(contest.id)">
                查看详情
              </el-button>
              <el-button 
                type="success" 
                round 
                v-if="canJoinContest(contest)"
                @click="joinContest(contest.id)"
              >
                立即参与
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-if="!loading && displayContests.length === 0" class="empty-container">
      <el-empty description="暂无竞赛" />
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        hide-on-single-page
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getContestList } from '@/api/contest'
import { Calendar, User, Picture, Search, Plus } from '@element-plus/icons-vue'

export default {
  name: 'ContestList',
  components: {
    Calendar,
    User,
    Picture,
    Search,
    Plus
  },
  setup() {
    const router = useRouter()
    const contests = ref([])
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const searchQuery = ref('')
    const statusFilter = ref('')
    const currentUser = ref(null)

    // 状态选项
    const statusOptions = [
      { value: '', label: '全部' },
      { value: '1', label: '进行中' },
      { value: '0', label: '待开始' },
      { value: '4', label: '已结束' }
    ]

    // 获取当前用户信息
    const getUserInfo = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        currentUser.value = JSON.parse(userInfoStr)
      }
    }

    // 判断当前用户是否有创建竞赛的权限（管理员或发起人）
    const canCreateContest = computed(() => {
      if (!currentUser.value) return false
      // 假设roleCode 1为管理员，2为发起人，3为参赛者
      return currentUser.value.roleCode === 1 || currentUser.value.roleCode === 2
    })

    // 获取竞赛列表
    const fetchContests = async () => {
      loading.value = true
      try {
        const params = {
          current: currentPage.value,
          size: pageSize.value,
          keyword: searchQuery.value,
          status: statusFilter.value,
          excludeStatus: 0 // 排除待审核状态(0)的竞赛
        }
        const res = await getContestList(params)
        contests.value = res.data.records
        total.value = res.data.total
      } catch (error) {
        ElMessage.error('获取竞赛列表失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    // 过滤后的竞赛列表
    const displayContests = computed(() => {
      return contests.value
    })

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchContests()
    }

    // 处理过滤
    const handleFilter = () => {
      currentPage.value = 1
      fetchContests()
    }

    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      fetchContests()
    }

    // 处理页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchContests()
    }

    // 跳转到创建竞赛页面
    const goToCreateContest = () => {
      router.push('/contest/create')
    }

    // 查看竞赛详情
    const viewContestDetail = (id) => {
      router.push(`/contest/detail/${id}`)
    }

    // 参与竞赛
    const joinContest = (id) => {
      // 这里可以添加逻辑判断用户是否已参与等
      // 先跳转到详情页
      router.push(`/contest/detail/${id}`)
    }

    // 是否可以参与竞赛（进行中且未满员）
    const canJoinContest = (contest) => {
      return contest.status === 1 && 
        (!contest.participantLimit || contest.currentParticipants < contest.participantLimit)
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待审核'
        case 1: return '进行中'
        case 2: return '已拒绝'
        case 3: return '已取消'
        case 4: return '已结束'
        default: return '未知状态'
      }
    }

    // 获取状态类名
    const getStatusClass = (status) => {
      switch (status) {
        case 0: return 'status-pending'
        case 1: return 'status-active'
        case 2: return 'status-rejected'
        case 3: return 'status-canceled'
        case 4: return 'status-ended'
        default: return ''
      }
    }

    // 截断文本
    const truncateText = (text, length) => {
      if (!text) return ''
      return text.length > length ? text.substring(0, length) + '...' : text
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未设置'
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    onMounted(() => {
      fetchContests()
      getUserInfo()
    })

    return {
      contests,
      loading,
      currentPage,
      pageSize,
      total,
      searchQuery,
      statusFilter,
      statusOptions,
      displayContests,
      canCreateContest,
      handleSearch,
      handleFilter,
      handleSizeChange,
      handleCurrentChange,
      viewContestDetail,
      joinContest,
      canJoinContest,
      getStatusText,
      getStatusClass,
      truncateText,
      formatDate,
      goToCreateContest
    }
  }
}
</script>

<style lang="scss" scoped>
.contest-list-container {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #2c3e50;
      font-size: 24px;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }

    .filter-container {
      display: flex;
      gap: 10px;

      .filter-item {
        width: 200px;
      }
    }
  }
  
  .contest-list {
    margin-bottom: 20px;
  }
  
  .contest-item-col {
    margin-bottom: 20px;
  }
  
  .contest-card {
    height: 100%;
    border-radius: 12px;
    overflow: hidden;
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-5px);
    }
    
    .contest-cover {
      position: relative;
      height: 180px;
      
      .cover-image {
        width: 100%;
        height: 100%;
      }
      
      .image-placeholder {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background-color: #f0f2f5;
        color: #909399;
      }
      
      .contest-status {
        position: absolute;
        top: 10px;
        right: 10px;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 12px;
        color: white;
        
        &.status-pending {
          background-color: #e6a23c;
        }
        
        &.status-active {
          background-color: #67c23a;
        }
        
        &.status-rejected {
          background-color: #f56c6c;
        }
        
        &.status-canceled {
          background-color: #909399;
        }
        
        &.status-ended {
          background-color: #409eff;
        }
      }
    }
    
    .contest-info {
      padding: 15px;
      
      .contest-title {
        margin: 0 0 10px;
        font-size: 18px;
        font-weight: bold;
        color: #2c3e50;
      }
      
      .contest-description {
        margin: 10px 0;
        font-size: 14px;
        color: #606266;
        line-height: 1.5;
        height: 42px;
        overflow: hidden;
      }
      
      .contest-meta {
        display: flex;
        gap: 15px;
        margin: 10px 0;
        
        .meta-item {
          display: flex;
          align-items: center;
          gap: 5px;
          color: #909399;
          font-size: 13px;
        }
      }
      
      .contest-actions {
        display: flex;
        gap: 10px;
        margin-top: 15px;
      }
    }
  }
  
  .loading-container {
    padding: 20px 0;
  }
  
  .empty-container {
    margin: 40px 0;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 